﻿using System;
using System.Collections.Generic;
using Unread.App.ViewModels;
using Unread.Business.Models;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Unread.App.Views
{
    public sealed partial class FeedItemPage : Unread.App.Common.LayoutAwarePage
    {
        public FeedItemViewModel ViewModel
        {
            get
            {
                return DataContext as FeedItemViewModel;
            }
        }

        public FeedItemPage()
        {
            this.InitializeComponent();

            DataContext = ServicesFactory.GetInstance<FeedItemViewModel>();
        }

        private void BottomAppBar1_Loaded(object sender, RoutedEventArgs e)
        {
            RegisterAppBarButtons();
        }

        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            if (pageState != null && pageState.ContainsKey("SelectedItem"))
                navigationParameter = pageState["SelectedItem"];

            var feedItemNavigationParameter = navigationParameter as FeedItemIdentifier;

            await ViewModel.Load(feedItemNavigationParameter.FeedId, feedItemNavigationParameter.FeedItemUri);
        }

        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            var selectedItem = this.flipView.SelectedItem;
            
            var feedItem = (selectedItem as ItemViewModel);
            if (feedItem != null)
                pageState["SelectedItem"] = new FeedItemIdentifier { FeedId = ViewModel.FeedId, FeedItemUri = feedItem.Link };
        }

        private void RegisterAppBarButtons()
        {
            Grid foo = BottomAppBar.Content as Grid;
            foreach (UIElement e in foo.Children)
            {
                foreach (UIElement c in ((StackPanel)e).Children)
                {
                    if (c.GetType() == typeof(Button))
                    {
                        base.StartLayoutUpdates(c, new RoutedEventArgs());
                    }
                }
            }
        }
    }
}